import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author meiqin liu（叶子）
 * @version 1.0.0
 * @date 2025/4/22 8:19
 */
//首次适应算法+合并
public class MemoryManager {
    public static List<MemoryBLock> memory = new ArrayList<>();
    static {
        //模拟系统占用后的内存
        memory.add(new MemoryBLock(0, 100));
    }

    public static boolean allocate(PCB pcb)
    {
        for(MemoryBLock block : memory)
        {
            if(block.isFree && block.size >= pcb.memorySize)
            {
                pcb.startAddress = block.startAddress;
                block.isFree = false;
                block.allocatedTo = pcb.pid;
                if(block.size > pcb.memorySize)
                {
                    memory.add(new MemoryBLock(block.startAddress + pcb.memorySize, block.size - pcb.memorySize));
                }
                block.size = pcb.memorySize;
                return true;
            }
        }
        return false;
    }

    public static void free(PCB pcb)
    {
        for(MemoryBLock block : memory)
        {
            if(block.startAddress == pcb.startAddress&&!block.isFree)
            {
                block.isFree = true;
                block.allocatedTo = "";
                merge();
                return;
            }
        }
    }
    public static void merge()
    {
        memory.sort(Comparator.comparingInt(b->b.startAddress));
        for(int i = 0;i < memory.size() - 1;i++)
        {
            MemoryBLock a = memory.get(i);
            MemoryBLock b = memory.get(i + 1);
            if(a.isFree && b.isFree){
                a.size += b.size;
                memory.remove(b);
                i--;//check again
            }
        }
    }
}

